const Router = require('koa-router')
const db = require('../db')
const path = require('path')
const fs = require('fs')

const router = new Router({ prefix: '/api/user' })

// 获取用户信息
router.get('/info', async (ctx) => {
  try {
    // 从请求参数中获取用户ID，如果未提供则默认为1（用于开发测试）
    const userId = ctx.query.userId || 1;
    
    // 获取用户基本信息
    const [user] = await db.query(`
      SELECT 
        id, 
        nickname, 
        avatar, 
        student_id,
        (SELECT COUNT(*) FROM bookings WHERE user_id = users.id AND status != 'cancelled') as courses_count
      FROM users 
      WHERE id = ?
    `, [userId])

    if (!user) {
      ctx.status = 404;
      ctx.body = { code: 404, message: '用户不存在' };
      return;
    }

    // 获取积分信息
    const [earnResults] = await db.query(
      'SELECT SUM(amount) as total FROM points_history WHERE user_id = ? AND type = "earn"',
      [userId]
    )
    
    const [spendResults] = await db.query(
      'SELECT SUM(amount) as total FROM points_history WHERE user_id = ? AND type = "spend"',
      [userId]
    )

    const points = Number(earnResults.total || 0)
    const usedPoints = Number(spendResults.total || 0)
    const availablePoints = points - usedPoints

    ctx.body = {
      code: 200,
      data: {
        ...user,
        points,
        availablePoints,
        coursesCount: user.courses_count
      }
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    ctx.status = 500
    ctx.body = { code: 500, message: '服务器内部错误' }
  }
})

// 获取用户详细信息
router.get('/profile', async (ctx) => {
  try {
    // 从请求参数中获取用户ID，如果未提供则默认为1（用于开发测试）
    const userId = ctx.query.userId || 1;
    
    const [user] = await db.query(`
      SELECT 
        id,
        nickname as name,
        avatar,
        student_id as studentId,
        gender,
        phone,
        email,
        school,
        major,
        grade,
        (SELECT COUNT(*) FROM bookings WHERE user_id = users.id AND status != 'cancelled') as coursesCount
      FROM users 
      WHERE id = ?
    `, [userId])

    if (!user) {
      ctx.status = 404
      ctx.body = { code: 404, message: '用户不存在' }
      return
    }

    ctx.body = { code: 200, data: user }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    ctx.status = 500
    ctx.body = { code: 500, message: '服务器内部错误' }
  }
})

// 更新用户信息
router.put('/profile', async (ctx) => {
  const { userId, name, gender, phone, email, school, major, grade } = ctx.request.body
  
  // 使用请求中的用户ID，如果未提供则默认为1（用于开发测试）
  const userIdToUpdate = userId || 1;

  try {
    await db.query(`
      UPDATE users 
      SET 
        nickname = ?,
        gender = ?,
        phone = ?,
        email = ?,
        school = ?,
        major = ?,
        grade = ?
      WHERE id = ?
    `, [name, gender, phone, email, school, major, grade, userIdToUpdate])

    ctx.body = { code: 200, message: '更新成功' }
  } catch (error) {
    console.error('更新用户信息失败:', error)
    ctx.status = 500
    ctx.body = { code: 500, message: '服务器内部错误' }
  }
})

// 添加头像上传接口
router.post('/upload/avatar', async (ctx) => {
  try {
    const file = ctx.request.files?.file
    if (!file) {
      throw new Error('没有接收到上传文件')
    }

    // 确保文件是图片
    if (!file.mimetype.startsWith('image/')) {
      throw new Error('只允许上传图片文件！')
    }

    // 从请求中获取用户ID
    const userId = ctx.request.body.userId || 1;
    
    const ext = path.extname(file.originalFilename)
    const fileName = `user${userId}${ext}`  // 使用固定的命名格式
    
    // 确保目标目录存在
    const targetDir = path.join(__dirname, '../public/uploads/images/avatars')
    if (!fs.existsSync(targetDir)) {
      fs.mkdirSync(targetDir, { recursive: true })
    }

    // 如果已存在同名文件，先删除
    const targetPath = path.join(targetDir, fileName)
    if (fs.existsSync(targetPath)) {
      fs.unlinkSync(targetPath)
    }

    // 移动文件
    const reader = fs.createReadStream(file.filepath)
    const writer = fs.createWriteStream(targetPath)
    
    await new Promise((resolve, reject) => {
      reader.pipe(writer)
      writer.on('finish', () => {
        // 删除临时文件
        fs.unlink(file.filepath, (err) => {
          if (err) {
            console.error('删除临时文件失败:', err)
          }
          resolve()
        })
      })
      writer.on('error', reject)
    })

    // 更新数据库中的头像URL
    const avatarUrl = `/uploads/images/avatars/${fileName}`
    await db.query(
      'UPDATE users SET avatar = ? WHERE id = ?',
      [avatarUrl, userId]
    )

    ctx.body = {
      code: 200,
      data: {
        url: avatarUrl
      },
      message: '头像上传成功'
    }
  } catch (error) {
    // 发生错误时也要清理临时文件
    if (ctx.request.files?.file) {
      fs.unlink(ctx.request.files.file.filepath, (err) => {
        if (err) {
          console.error('删除临时文件失败:', err)
        }
      })
    }

    console.error('头像上传失败:', error)
    ctx.status = 500
    ctx.body = {
      code: 500,
      message: error.message || '头像上传失败'
    }
  }
})

module.exports = router